package com.xl.studentpass.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xl.studentpass.component.WebSocket;
import com.xl.studentpass.entity.ImageInfoEntity;
import com.xl.studentpass.entity.OrderInfoEntity;
import com.xl.studentpass.entity.TaskInfoEntity;
import com.xl.studentpass.entity.UserEntity;
import com.xl.studentpass.entity.po.OrderOverViewPo;
import com.xl.studentpass.entity.vo.OrderVo;
import com.xl.studentpass.mapper.AcceptTaskMapper;
import com.xl.studentpass.mapper.ImageMapper;
import com.xl.studentpass.mapper.PublishTaskMapper;
import com.xl.studentpass.mapper.UserMapper;
import com.xl.studentpass.service.AcceptTaskService;
import com.xl.studentpass.utils.ImageIdType;
import com.xl.studentpass.utils.LocalDateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.xl.studentpass.utils.PublicStaticConstant.*;
import static com.xl.studentpass.utils.TaskOrderStatus.*;

/**
 * @author: xl
 * @createTime: 2023/5/29 20:30:30
 * @program: student-pass
 * @e-mail: 2199396150@qq.com
 * @description:
 */
@Service
@Slf4j
public class AcceptTaskServiceImpl extends ServiceImpl<AcceptTaskMapper, OrderInfoEntity> implements AcceptTaskService {

    @Resource
    PublishTaskMapper publishTaskMapper;
    @Resource
    UserMapper userMapper;
    @Resource
    WebSocket webSocket;
    @Resource
    RedisTemplate<String, Object> redisTemplate;
    @Value("${redis.order.key}")
    private String orderKey;
    @Value("${redis.task.key}")
    private String taskKey;
    @Resource
    ImageMapper imageMapper;

    /**
     * 接单
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer create(Map<String, Integer> orderMap) {
        Integer inUserId = orderMap.get("userId");
        if (ObjectUtils.isEmpty(inUserId)) {
            log.info("传入数据为空");
            return -1;
        }

        int loginUserId = StpUtil.getLoginIdAsInt();

        if (!inUserId.equals(loginUserId)) {
            log.info("登录用户不等于传入数据的用户");
            return -1;
        }

        Integer taskId = orderMap.get("taskId");

        log.info("taskId=====>" + taskId);

        TaskInfoEntity taskInfo = publishTaskMapper.selectById(taskId);

        if (taskInfo.getValid().equals(1) || (
                !taskInfo.getStatusId().equals(NO_ORDER_RECEIVED.getId()) &&
                        !taskInfo.getStatusId().equals(ORDER_CANCEL.getId()))
        ) {
            log.info("订单状态不满足需求");
            return -1;
        }

        if (inUserId.equals(taskInfo.getUserId())) {
            log.info("任务发布者与任务接受者一样");
            return -1;
        }

        Integer orderUserSchoolId = getSchoolIdByUserId(inUserId);
        Integer taskUserSchoolId = getSchoolIdByUserId(taskInfo.getUserId());

        if (orderUserSchoolId.equals(-1) || !orderUserSchoolId.equals(taskUserSchoolId)) {
            log.info("任务发布地不同");
            return -1;
        }

        taskInfo.setStatusId(ORDER_RECEIVED.getId());
        String localDateTimeStr = LocalDateUtils.getLocalDateTimeStr();
        taskInfo.setOperaTime(localDateTimeStr);

        int i = publishTaskMapper.updateById(taskInfo);
        if (i < 1) {
            throw new RuntimeException("任务表更新失败");
        }
        log.info("更新任务表====>" + taskInfo);
        Integer orderId = null;
        try {
            OrderInfoEntity orderInfo = new OrderInfoEntity();
            orderInfo.setUserId(inUserId);
            orderInfo.setTaskId(taskId);
            orderInfo.setCreateTime(localDateTimeStr);
            orderInfo.setValid(IS_VALIDITY_ORDER);
            orderInfo.setStatusId(ORDER_RECEIVED.getId());
            boolean b = this.saveOrUpdate(orderInfo);
            orderId = orderInfo.getId();
            if (!b) {
                throw new RuntimeException("订单表插入失败");
            }
            //取消redis过期订单监控
            redisTemplate.delete(orderKey + taskInfo.getId());
            //通知任务发布者
            sendMessage(taskInfo, orderInfo, "accept");

        } catch (RuntimeException e) {
            log.error(e.getMessage());
            throw new RuntimeException("订单表插入失败");
        }
        return orderId;
    }

    /**
     * 取消任务
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer cancel(OrderVo orderVo) {

        if (ObjectUtils.isEmpty(orderVo) || ObjectUtils.isEmpty(orderVo.getOrderId())) {
            return -1;
        }

        Integer orderId = orderVo.getOrderId();

        OrderInfoEntity orderInfo = this.getById(orderId);
        BeanUtil.copyProperties(orderVo, orderInfo);

        if (ObjectUtils.isEmpty(orderInfo)) {
            return -1;
        }
        TaskInfoEntity taskInfo = publishTaskMapper.selectById(orderInfo.getTaskId());
        if (ObjectUtils.isEmpty(taskInfo)) {
            return -1;
        }
        String expirationTime = taskInfo.getExpirationTime();
        String nowTime = LocalDateUtils.getLocalDateTimeStr();
        long validTimeSeconds = LocalDateUtils.getValidTimeSeconds(nowTime, expirationTime);

        if (validTimeSeconds <= OVERDUE_THRESHOLD) {
            taskInfo.setStatusId(ORDER_COMPLETION.getId());
            redisTemplate.delete(orderKey + taskInfo.getId());
        } else {
            taskInfo.setStatusId(ORDER_CANCEL.getId());
        }
        taskInfo.setOperaTime(nowTime);
        int i = publishTaskMapper.updateById(taskInfo);
        if (i <= 0) {
            return -1;
        }
        orderInfo.setStatusId(ORDER_CANCEL.getId());
        orderInfo.setIsCompletion(NO_VALIDITY_ORDER);
        boolean b = this.saveOrUpdate(orderInfo);
        if (!b) {
            throw new RuntimeException("更新接单表异常");
        }
        sendMessage(taskInfo, orderInfo, "cancel");
        return orderInfo.getId();
    }

    /**
     * 完成任务
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer complete(OrderVo orderVo) {
        if (ObjectUtils.isEmpty(orderVo) || ObjectUtils.isEmpty(orderVo.getImageIds())) {
            log.info("没有图片数据");
            return -1;
        }

        List<ImageInfoEntity> imageInfos = imageMapper.selectBatchIds(orderVo.getImageIds());
        if (imageInfos.size() <= 0) {
            log.info("传入的图片id没有查询到数据");
            return -1;
        }

        OrderInfoEntity orderInfo = this.getById(orderVo.getOrderId());

        if (ObjectUtils.isEmpty(orderInfo)) {
            log.info("没有订单数据");
            return -1;
        }
        //获取任务信息
        TaskInfoEntity taskInfo = publishTaskMapper.selectById(orderInfo.getTaskId());

        if (ObjectUtils.isEmpty(taskInfo)) {
            log.info("没有任务数据");
            return -1;
        }
        //更改任务状态
        String localDateTime = LocalDateUtils.getLocalDateTimeStr();
        taskInfo.setStatusId(ORDER_CONFIRM.getId());
        taskInfo.setOperaTime(localDateTime);

        int update = publishTaskMapper.updateById(taskInfo);
        if (update < 1) {
            throw new RuntimeException("更新任务表异常");
        }
        //更改接单表状态
        orderInfo.setIsCompletion(IS_VALIDITY_ORDER);
        orderInfo.setStatusId(ORDER_CONFIRM.getId());
        orderInfo.setCompletionTime(localDateTime);
        boolean b = this.updateById(orderInfo);
        if (!b) {
            throw new RuntimeException("更新接单表异常");
        }

        HashMap<String, Object> redisMessage = new HashMap<>();

        redisMessage.put("taskId", orderInfo.getTaskId());
        redisMessage.put("accepter", orderInfo.getUserId());
        redisMessage.put("publisher", taskInfo.getUserId());
        redisMessage.put("taskName", taskInfo.getTaskName());

        redisTemplate.opsForValue().set(taskKey + "%" + JSON.toJSONString(redisMessage), 1, TASK_OVERDUE_TIME, TimeUnit.MINUTES);
        sendMessage(taskInfo, orderInfo, "finish");
        return orderInfo.getId();
    }

    @Override
    public Integer delete(OrderVo orderVo) {
        int longUserId = StpUtil.getLoginIdAsInt();
        if (orderVo.getUserId().equals(longUserId)) {
            return -1;
        }
        boolean b = this.removeById(orderVo.getOrderId());
        return b ? 1 : -1;
    }

    /**
     * 获取接受的订单详情
     */
    @Override
    public OrderOverViewPo viewOrderDetails(OrderVo orderVo) {

        OrderOverViewPo orderViewPo = publishTaskMapper.queryOrderOverViewPo(orderVo.getUserId(), orderVo.getOrderId());
        List<String> imageUrls = getImageUrls(orderViewPo.getOrderId());

        if (!ObjectUtils.isEmpty(imageUrls) && imageUrls.size() > 0) {
            orderViewPo.setImageUrls(imageUrls);
        }
        return orderViewPo;
    }

    private List<String> getImageUrls(Integer id) {
        return getStrings(id, imageMapper, ImageIdType.ORDER);
    }

    private void sendMessage(TaskInfoEntity taskInfo, OrderInfoEntity orderInfo, String operate) {
        //通知任务发布者
        HashMap<String, Object> messages = new HashMap<>();

        messages.put("orderId", taskInfo.getId());
        messages.put("taskName", taskInfo.getTaskName());
        messages.put("createTime", taskInfo.getCreateTime());
        messages.put("orderUserId", orderInfo.getUserId());
        messages.put("operate", operate);

        webSocket.sendOneMessage(String.valueOf(taskInfo.getUserId()), JSON.toJSONString(messages));
    }

    private Integer getSchoolIdByUserId(Integer userId) {
        UserEntity user = userMapper.selectById(userId);
        if (ObjectUtils.isEmpty(user)) {
            return -1;
        }
        return user.getSchoolId();
    }

    @NotNull
    static List<String> getStrings(Integer id, ImageMapper imageMapper, ImageIdType idType) {
        QueryWrapper<ImageInfoEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(idType.getName(), id);
        List<ImageInfoEntity> imageInfos = imageMapper.selectList(wrapper);
        ArrayList<String> urls = new ArrayList<>();
        imageInfos.forEach(x -> urls.add(x.getImageUrl()));
        return urls;
    }
}
